package top.changelife.learn.springmvc.socket.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author cz
 * @date 2019/12/21 11:31
 */
public class Server {
    public static void main(String[] args) {
        try {
            // 监听 8080 端口
            ServerSocket server = new ServerSocket(8080);
            // 等待请求，阻塞
            Socket socket = server.accept();
            // 接收到请求以后，读取流中的数据
            BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line = is.readLine();
            System.out.println("received from client: " + line);
            // 发送数据
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            pw.println("received data: " + line);
            pw.flush();
            // 关闭资源
            pw.close();
            is.close();
            socket.close();
            server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
